import configparser
import json
from pathlib import Path

class ConfigManager:
    def __init__(self):
        self.config_dir = Path.home() / ".baidupan"
        self.config_file = self.config_dir / "config.ini"
        self.tokens_file = self.config_dir / "tokens.json"
        
        # 确保配置目录存在
        if not self.config_dir.exists():
            self.config_dir.mkdir(parents=True, exist_ok=True)
    
    def load_config(self):
        """加载配置文件"""
        config = configparser.ConfigParser()
        if self.config_file.exists():
            config.read(self.config_file)
        return config
    
    def save_config(self, config_data):
        """保存配置到文件"""
        config = configparser.ConfigParser()
        
        # 直接设置DEFAULT段的配置
        config['DEFAULT'] = {
            'client_id': config_data.get('client_id', ''),
            'client_secret': config_data.get('client_secret', ''),
            'redirect_uri': config_data.get('redirect_uri', 'urn:ietf:wg:oauth:2.0:oob')
        }
        
        with open(self.config_file, 'w') as f:
            config.write(f)

    def save_config_old(self, config_data):
        """保存配置到文件"""
        config = configparser.ConfigParser()
        
        # 添加默认配置
        config['DEFAULT'] = {
            'client_id': config_data.get('client_id', ''),
            'client_secret': config_data.get('client_secret', ''),
            'redirect_uri': config_data.get('redirect_uri', 'urn:ietf:wg:oauth:2.0:oob')
        }
        
        with open(self.config_file, 'w') as f:
            config.write(f)
    
    def load_tokens(self):
        """加载令牌信息"""
        if self.tokens_file.exists():
            try:
                with open(self.tokens_file, 'r') as f:
                    return json.load(f)
            except:
                return {}
        return {}
    
    def save_tokens(self, tokens):
        """保存令牌信息"""
        with open(self.tokens_file, 'w') as f:
            json.dump(tokens, f, indent=2)
    
    def get_client_id(self):
        """获取客户端ID"""
        config = self.load_config()
        return config.get('DEFAULT', 'client_id', fallback='')
    
    def get_client_secret(self):
        """获取客户端密钥"""
        config = self.load_config()
        return config.get('DEFAULT', 'client_secret', fallback='')
    
    def get_redirect_uri(self):
        """获取重定向URI"""
        config = self.load_config()
        return config.get('DEFAULT', 'redirect_uri', fallback='urn:ietf:wg:oauth:2.0:oob')
